package com.design.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.design.reggie.common.Result;
import com.design.reggie.entity.User;
import com.design.reggie.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result<User> login(@RequestBody User user, HttpServletRequest request) {
        // 获取前端提交的账号密码
        String phone = user.getPhone();
        String password = user.getPassword();
        // md5加密，并重新赋值给password
        password = DigestUtils.md5Hex(password);

        // 根据页面提交的phone查询用户，封装为user1
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, phone);
        User user1 = userService.getOne(queryWrapper);

        //如果没有查询到用户则登录失败
        if (user1 == null) {
            user.setPassword(password);
            userService.save(user);
            request.getSession().setAttribute("user", user.getId());
            return Result.success(user);
        }

        // 密码比对，如果不一致，则登录失败
        if (!user1.getPassword().equals(password)) {
            return Result.error("密码错误，请输入正确的密码");
        }

        // 查询员工状态是否正常，若被禁用则登录失败
        if (user1.getStatus() != 1) {
            return Result.error("账号已被禁用");
        }

        // 以上都不成立，则登录成功，将员工id存入session，并返回登录成功
        request.getSession().setAttribute("user", user1.getId());
        return Result.success(user1);

    }

    /**
     * 用户退出登录
     * @return
     */
    @PostMapping("/loginout")
    public Result<String> logout(HttpServletRequest request) {

        request.getSession().removeAttribute("user");
        return Result.success("退出登录成功");
    }
}
